% Matlab Code for replication of "Optimal Debt Maturity and Firm Investment"
% by J. Jungherr and I. Schott, September 2020
% Solve period T-x

setup_matrices % Creates empty matrices

for zz = 1:lenz    
    for bb = 1:lenb  
        
        % Define firm-level state
        S.DEBT  = PARMS.DEBT{zz}(bb);
        S.zz    = zz;
 
        % Create initial guess and bounds (These bounds should not bind after convergence of the solution!)
        firm_problem_initial_guess
        
        % SOLVE THE FIRM PROBLEM
        optimum = fminsearchbnd(@(x) firm_optim(x,S,PARMS,VAL),opt_ini,lb,ub,PARMS.options_fmsb);                
        
        % Obtain remaining variables at optimum
        [~, eq_out] = firm_optim(optimum,S,PARMS,VAL,1);
        
        % Save policy functions 
        compute_policy_functions
        
    end % End of B loop
end % End of Z loop

save_history 
VAL.period = VAL.period + 1;
err_v       = (value_pol(1) - VAL.vF(1));
    
VAL.cap_pol     = cap_pol;
VAL.lev_pol     = lev_pol;
VAL.lab_pol     = lab_pol;
VAL.mat_pol     = mat_pol;

build_interpol_functions
